package com.todod.common.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HtmlToWord {

	static Logger logger = LoggerFactory.getLogger(HtmlToWord.class);

	public static void htmlToWord(String html, OutputStream out, String abstractPath) {

		html = html.replaceAll("<table", "<table border='1' ");
//		try {
//			html = repUrl(html);
//		} catch (IOException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
		html = closeHTML(html);
		try {

			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("html", html);
			PDFTemplateUtil util = new PDFTemplateUtil();
			util.setTemplateFileName("template.ftl");
			util.setTemplatePath("/static/ftl");
			util.createPDF(dataMap, out, abstractPath);
		} catch (Exception e) {
			logger.error("error-info", e);
		}
	}

	public static String repUrl(String htmlData) throws FileNotFoundException, IOException {
		Set<String> pics = new HashSet<String>();
		String img = "";
		Pattern p_image;
		Matcher m_image;
		String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
		// String regEx_img = "<img\\s*([^>]*)\\s*src=\\\"(.*?)\\\"\\s*([^>]*)>";
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(htmlData);
		// System.out.println(htmlData);
		while (m_image.find()) {
			// 得到<img />数据
			img = m_image.group();
			// 匹配<img>中的src数据
			Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
			while (m.find()) {
				File tempFile = new File(m.group(1).trim());
				BufferedImage sourceImg = ImageIO.read(new FileInputStream(tempFile));
				String fileName = tempFile.getPath();
				if (sourceImg.getWidth() <= 700) {
					htmlData = htmlData.replace(m.group(), "width=" + "'" + sourceImg.getWidth() + "'" + " height="
							+ "'" + sourceImg.getHeight() + "'" + " " + m.group());
				} else {
					htmlData = htmlData.replace(m.group(), "width='700' " + m.group());
				}
				htmlData = htmlData.replace(m.group(1), fileName);
			}
		}
		return htmlData;
	}

	public static String closeHTML(String str) {
		List arrTags = new ArrayList();
		arrTags.add("br");
		arrTags.add("hr");
		arrTags.add("img");
		arrTags.add("input");
		arrTags.add("param");
		arrTags.add("meta");
		arrTags.add("link");
		for (int i = 0; i < arrTags.size(); i++) {
			for (int j = 0; j < str.length();) {
				int tagStart = str.indexOf("<" + arrTags.get(i), j);
				if (tagStart >= 0) {
					int tagEnd = str.indexOf(">", tagStart);
					j = tagEnd;
					String preCloseTag = str.substring(tagEnd - 1, tagEnd);
					if (!"/".equals(preCloseTag)) {
						String preStr = str.substring(0, tagEnd);
						String afterStr = str.substring(tagEnd);
						str = preStr + "/" + afterStr;
					}
				} else {
					break;
				}
			}
		}
		return str;
	}

}
